package com.xmrecruit.permission

/*

 * Copyright 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings

import com.xmrecruit.CC
import com.xmrecruit.util.ToastUtil

import java.util.ArrayList

/**
 * Utility class that wraps access to the runtime permissions API in M and
 * provides basic helper methods.
 */
object PermissionUtil {
    val PERMISSIONSREQUEST = 1
    val PERMISSION_CAMERA = "摄像头"
    val PERMISSION_PHONE = "拨打电话"
    val PERMISSION_LOCATION = "定位"
    val PERMISSION_AUDIO = "录音"
    val PERMISSION_STORAGE = "存储"
    val PERMISSION_SMS = "短信"
    val PERMISSION_SETTING = "舶来汇需要允许修改系统设置的权限，是否去设置"
    var OVERLAY_PERMISSION_REQ_CODE = 1234
    var OVERLAY_PERMISSION_REQ_CODE_FOR_PARKING = 1235
    var WRITESETTING_PERMISSION_REQ_CODE = 1236

    var Photo_permission = arrayOf(Manifest.permission.CAMERA)
    var Photo_permissionMessage = arrayOf(PermissionUtil.PERMISSION_CAMERA)

    /**
     * Check that all given permissions have been granted by verifying that each
     * entry in the given array is of the value
     * [PackageManager.PERMISSION_GRANTED].

     * @see Activity.onRequestPermissionsResult
     */
    fun verifyPermissions(grantResults: IntArray): Boolean {
        // Verify that each required permission has been granted, otherwise
        // return false.
        for (result in grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    /**
     * Returns true if the Activity has access to all given permissions. Always
     * returns true on platforms below M.

     * @see Activity.checkSelfPermission
     */
    fun hasSelfPermission(activity: Activity,
                          permissions: Array<String>): Boolean {
        // Below Android M all permissions are granted at install time and are
        // already available.
        if (!isMNC) {
            return true
        }

        // Verify that all required permissions have been granted
        for (permission in permissions) {
            if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    private fun SwitchToMessage(permission: String): String {
        if (permission == Manifest.permission.CAMERA) {
            return PERMISSION_CAMERA
        } else if (permission == Manifest.permission.READ_PHONE_STATE) {
            return PERMISSION_PHONE
        } else if (permission == Manifest.permission.ACCESS_COARSE_LOCATION) {
            return PERMISSION_LOCATION
        } else if (permission == Manifest.permission.WRITE_EXTERNAL_STORAGE) {
            return PERMISSION_STORAGE
        } else if (permission == Manifest.permission.RECORD_AUDIO) {
            return PERMISSION_AUDIO
        } else if (permission == Manifest.permission.ACCESS_FINE_LOCATION) {
            return PERMISSION_LOCATION
        }else if (permission == Manifest.permission.RECEIVE_SMS) {
            return PERMISSION_SMS
        }
        return ""
    }

    fun BuildWarning(permission: List<String>): String {
        if (permission.size > 0) {
            // Need Rationale
            var message = "本应用需要" + SwitchToMessage(permission[0])
            for (i in 1..permission.size - 1)
                message = message + "、" + SwitchToMessage(permission[i])

            return message + "权限"
        }
        return ""

    }

    /**
     * @param activity
     * *
     * @param permissions
     * *
     * @param dialogMessage 如果请求了被用户标记不再提示的权限，弹出对话框提示用户
     */
    fun CheckSelfPermission(activity: Activity,
                            permissions: Array<String>, dialogMessage: Array<String>): Boolean {
        val permissionsNeeded = ArrayList<String>()
        val permissionsList = ArrayList<String>()
        for (i in permissions.indices) {
            val permission = permissions[i]
            if (!addPermission(activity, permissionsList, permission))
                permissionsNeeded.add(dialogMessage[i])
        }

        if (permissionsList.size > 0) {
            if (permissionsNeeded.size > 0) {
                // Need Rationale
                var message = "您需要为本应用授权" + permissionsNeeded[0]
                for (i in 1..permissionsNeeded.size - 1)
                    message = message + "、" + permissionsNeeded[i]
                activity.requestPermissions(permissionsList
                        .toTypedArray(),
                        PermissionUtil.PERMISSIONSREQUEST)
                return false
            }
            activity.requestPermissions(
                    permissionsList.toTypedArray(),
                    PermissionUtil.PERMISSIONSREQUEST)
            return false
        }
        return true
    }

    private fun showMessageOKCancel(message: String) {
        // new AlertDialog.Builder(activity).setMessage(message)
        // .setPositiveButton(R.string.sure, okListener)
        // .setNegativeButton(R.string.cancel, null).create().show();
        ToastUtil.showStringToast(CC.applicationContext, message)
    }

    fun CheckWritingPermission(context: Context): Boolean {
        try {
            if (isMNC && !Settings.System.canWrite(context)) {
                ToastUtil.showStringToast(CC.applicationContext, "请在该设置页面勾选，才可以使用路况提醒功能")
                val selfPackageUri = Uri.parse("package:" + context.packageName)
                val intent = Intent(
                        Settings.ACTION_MANAGE_WRITE_SETTINGS, selfPackageUri)
                context.startActivity(intent)
                return false
            }
        } catch (e: Exception) {
            return true
        }

        return true
    }

    fun CheckWritingPermissionSplash(context: Context): Boolean {
        try {
            if (isMNC && !Settings.System.canWrite(context)) {
                val selfPackageUri = Uri.parse("package:" + context.packageName)
                val intent = Intent(
                        Settings.ACTION_MANAGE_WRITE_SETTINGS, selfPackageUri)
                (context as Activity).startActivityForResult(intent,
                        WRITESETTING_PERMISSION_REQ_CODE)
                return false
            }
        } catch (e: Exception) {
            return true
        }

        return true
    }

    fun CanWriteSetting(context: Context): Boolean {
        if (!isMNC) {
            return true
        }
        return Settings.System.canWrite(context)
    }

    private val ischecked = false

    //    public static void CheckcanDrawOverlaysPermission(Context context) {
    //	if (isMNC() && !Settings.canDrawOverlays(context)) {
    //	    Intent intent = new Intent(
    //		    Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
    //		    Uri.parse("package:" + context.getPackageName()));
    //	    ((Activity) (context)).startActivityForResult(intent,
    //		    OVERLAY_PERMISSION_REQ_CODE);
    //	} else {
    //	    WindowUtils.getInstance().showPopupWindow(context);
    //	}
    //    }

    //    public static void CheckcanDrawOverlaysPermissionShow(Context context) {
    //	if (isMNC() && Settings.canDrawOverlays(context)) {
    //	    WindowUtils.getInstance().showPopupWindow(context);
    //	} else if (!isMNC()) {
    //	    WindowUtils.getInstance().showPopupWindow(context);
    //	}
    //    }

    fun CheckcanDrawOverlaysPermissionOnly(context: Context,
                                           requestcode: Int) {
        if (isMNC && !Settings.canDrawOverlays(context)) {
            val intent = Intent(
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + context.packageName))
            (context as Activity).startActivityForResult(intent, requestcode)
        }
    }

    fun HaveDrawOverlaysPermissionOnly(context: Context): Boolean {
        if (!isMNC) {
            return true
        }
        return Settings.canDrawOverlays(context)
    }

    private fun addPermission(activity: Activity,
                              permissionsList: MutableList<String>, permission: String): Boolean {
        if (!hasSelfPermission(activity, permission)) {
            permissionsList.add(permission)
            // Check for Rationale Option
            if (!activity.shouldShowRequestPermissionRationale(permission))
                return false
        }
        return true
    }

    /**
     * Returns true if the Activity has access to a given permission. Always
     * returns true on platforms below M.

     * @see Activity.checkSelfPermission
     */
    fun hasSelfPermission(activity: Activity, permission: String): Boolean {
        // Below Android M all permissions are granted at install time and are
        // already available.
        if (!isMNC) {
            return true
        }

        return activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
    }

    /*
	 * TODO: In the Android M Preview release, checking if the platform is M
	 * is done through the codename, not the version code. Once the API has
	 * been finalised, the following check should be used:
	 */// return "MNC".equals(Build.VERSION.CODENAME);
    val isMNC: Boolean
        get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M

}

